from flask import Flask, request, jsonify
from flask_cors import CORS
import sys
import os
import json
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from models.bart import generate_bart, test_bart

app = Flask(__name__)
CORS().init_app(app)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/summarize', methods=['POST'])
def summarize():
    data = request.get_json()
    input_texts = data.get('texts', [])
    model_type = data.get('model_type', '')
    if isinstance(input_texts, str):
        input_texts = [input_texts]  # 如果是单个字符串，转换为列表
    summaries = generate_bart(input_texts, model_type)
    return jsonify({'summaries': summaries})

@app.route('/summarize_json', methods=['POST'])
def summarize_json():
    try:
        # 检查请求中是否包含 JSON 文件和模型名称
        if 'file' not in request.files or 'model' not in request.form:
            return jsonify({"error": "Missing 'file' or 'model_name' in the request."}), 400

        # 获取 JSON 文件和模型名称
        file = request.files['file']
        model_name = request.form['model']

        # 保存上传的 JSON 文件到临时目录
        temp_file_path = 'temp_input.json'
        file.save(temp_file_path)

        # 调用 test_bart 函数进行摘要评估
        test_report = test_bart(temp_file_path, model_name)

        # 删除临时文件
        os.remove(temp_file_path)

        # 返回评估报告
        return jsonify(test_report)

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/summarizes', methods=['POST'])
def summarizes():
    try:
        # 检查请求中是否包含 JSON 文件和模型名称
        if 'file' not in request.files or 'model' not in request.form:
            return jsonify({"error": "Missing 'file' or 'model' in the request."}), 400

        # 获取 JSON 文件和模型名称
        file = request.files['file']
        model_name = request.form['model']

        # 保存上传的 JSON 文件到临时目录
        temp_file_path = 'temp_input.json'
        file.save(temp_file_path)

        # 读取 JSON 文件内容
        with open(temp_file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        # 提取原文列表
        original_texts = [item.get('content', '') for item in data]

        # 调用 generate_bart 函数进行摘要生成
        generated_summaries = generate_bart(original_texts, model_name)

        # 假设参考摘要暂时为空，你可以根据实际情况修改
        reference_summaries = [item.get('title', '') for item in data]

        # 构建返回数据
        result = []
        for i, (original_text, reference_summary, generated_summary) in enumerate(zip(original_texts, reference_summaries, generated_summaries), start=1):
            result.append({
                "id": i,
                "originalText": original_text,
                "referenceSummary": reference_summary,
                "generatedSummary": generated_summary
            })

        # 删除临时文件
        os.remove(temp_file_path)

        # 返回评估报告
        return jsonify(result)

    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run()